const Service = require('egg').Service;

const DBCFG = require('../dbcfg/dbconfig')

// 初始化模型
const models = DBCFG.getModels()

class $TABLE_NAME$Service extends Service {
  async list(offset,limit) {
    const { count, rows } = await models.$TABLE_NAME$.findAndCountAll({
        order: [
          ['$PRIMARYKEY$', 'DESC']  // 按ID倒序排序
        ],
        offset: Number(offset),
        limit: Number(limit)
      })
    return {
      total:count,
      items:rows
    }
  }
  async detail(_$PRIMARYKEY$){
    const res = await models.$TABLE_NAME$.findOne({
        where: {
          $PRIMARYKEY$: _$PRIMARYKEY$
        }
      })
    return res
  }
  async add(objData) {
    const res = await models.$TABLE_NAME$.create(objData)
    return res
  }

  async del(_$PRIMARYKEY$){
    var obj = await models.$TABLE_NAME$.findOne({
        where: {
          $PRIMARYKEY$: _$PRIMARYKEY$
        }
      })
    if(!obj){

      return {
        code:400,
        msg:'数据不存在'
      }
    } else {
      const res = await models.$TABLE_NAME$.destroy({
        where: {
          $PRIMARYKEY$: _$PRIMARYKEY$
        }
      })
      return {
        code:200,
        msg:'删除成功'
      }
    }
  }
  
  async update(objData){
    var _$PRIMARYKEY$ = objData.$PRIMARYKEY$;
    
    var obj = await models.$TABLE_NAME$.findOne({
        where: {
          $PRIMARYKEY$: _$PRIMARYKEY$
        }
      })
    if(!obj){
      return {
        code:400,
        msg:'数据不存在'
      }
    }

    const res = await models.$TABLE_NAME$.update(objData,{
      where: {
        $PRIMARYKEY$: _$PRIMARYKEY$
      }
    })
    return res;

  }

}

module.exports = $TABLE_NAME$Service;